package unimelb.filesync.common.network;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import unimelb.filesync.common.message.NetworkMessage;
import unimelb.filesync.common.misc.JsonConverter;

public class NetworkService {

    private final JsonConverter jsonConverter;

    public NetworkService() {
        super();
        this.jsonConverter = new JsonConverter();
    }

    public void writeMessage(NetworkMessage msg, NetworkConnection conn) {
        final String jsonStr = jsonConverter.toJson(msg);
        conn.writeString(jsonStr);
    }

    public NetworkMessage readMessage(NetworkConnection conn) {
        final String jsonStr = conn.readString();
        if (jsonStr != null) {
            return jsonConverter.fromJson(jsonStr);
        } else {
            return null;
        }
    }

    public NetworkConnection connectToServer(String host, int port) {
        try {
            final Socket socket = new Socket(host, port);
            return new NetworkConnection(socket);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public NetworkConnection acceptConenction(ServerSocket serverSocket) {
        try {
            final Socket socket = serverSocket.accept();
            return new NetworkConnection(socket);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
